package utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static SqlSession openSession;


//    创建SqlSessionFactory
    public static SqlSessionFactory getFactory(){
        try {
            String resource = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(is);
            return factory;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }

    }

//    生成SqlSession
    public static SqlSession getSqlSession(boolean isAutoCommit){
//        获取SqlSessionFactory
        SqlSessionFactory factory=getFactory();
        openSession = factory.openSession(isAutoCommit);
        return openSession;
    }

//    关闭
    public void destroy(){
        openSession.close();
    }
}
